package jsyf.oa.service.system;

import com.alibaba.dubbo.common.utils.StringUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import jsyf.com.util.FastJsonConvert;
import jsyf.oa.dao.system.BigAchievementsDao;
import jsyf.oa.dao.system.RoleDao;
import jsyf.oa.dao.system.User2RegionDao;
import jsyf.oa.dao.system.UserAchievementsDao;
import jsyf.oa.entity.system.BigAchievementsEntity;
import jsyf.oa.entity.system.RoleEntity;
import jsyf.oa.entity.system.UserAchievementsEntity;
import jsyf.oa.facade.system.BigAchievementsFacade;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2018/8/2 0002.
 */
@Service
@Transactional(rollbackFor = Exception.class)
@com.alibaba.dubbo.config.annotation.Service(protocol = {"dubbo"})
public class BigAchievementsService implements BigAchievementsFacade {
    @Autowired
    private BigAchievementsDao bigachievementsDao;

    @Autowired
    private UserAchievementsDao userAchievementsDao;

    @Autowired
    private User2RegionDao user2RegionDao;
    @Autowired
    private RoleDao roleDao;

    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");

    @Override
    public JSONObject getListByBigAreaId(String jsonData) {
        JSONObject jsonParams = FastJsonConvert.convertJSONToObject(jsonData, JSONObject.class);
        String bigAreaId = jsonParams.getString("bigAreaId");
        String month = sdf.format(new Date());
        StringBuffer condition = new StringBuffer();
        condition.append("AND t_sys_big_achievements.BIG_AREA_ID= '" + bigAreaId + "'\n");
        condition.append("AND t_sys_big_achievements.MONTH= '" + month + "'\n");
        List<Object> sqlArgs = new ArrayList<Object>();
        JSONObject records = bigachievementsDao.getListByBigAreaId(condition.toString());
        // 子数组对象
        JSONObject result = new JSONObject();
        result.put("records", records);
        return result;
    }

    @Override
    public JSONObject getPeopleFineByCompanyId(String jsonData) {
        JSONObject jsonParams = FastJsonConvert.convertJSONToObject(jsonData, JSONObject.class);
        String companyId = jsonParams.getString("companyId");
        String day = jsonParams.getString("day");
        String month = day.substring(0, 7);
        List<JSONObject> list = bigachievementsDao.getPeopleFineByCompanyId(companyId, month, day);
       /* String RegionalId = "";
        String RegionalName = "";
        String DirectorId = "";
        String DirectorName = "";
        String GeneralId = "";
        String GeneralName = "";
        for (JSONObject json : list) {
            if (json.getString("roleName").equals("区域总监")) {
                RegionalId = json.getString("userId");
                RegionalName = json.getString("userName");
            } else if (json.getString("roleName").equals("销售总监")) {
                DirectorId = json.getString("userId");
                DirectorName = json.getString("userName");
            } else if (json.getString("roleName").equals("总经理")) {
                GeneralId = json.getString("userId");
                GeneralName = json.getString("userName");
            }
        }
        for (JSONObject json : list) {
            if (json.getString("roleName").equals("大区经理") && StringUtils.isEmpty(json.getString("userId"))) {
                if (StringUtils.isNotEmpty(RegionalId)) {
                    json.put("userId", RegionalId);
                    json.put("userName", RegionalName);
                } else if (StringUtils.isNotEmpty(DirectorId)) {
                    json.put("userId", DirectorId);
                    json.put("userName", DirectorName);
                } else {
                    json.put("userId", GeneralId);
                    json.put("userName", GeneralName);
                }
            }
        }*/
        JSONObject result = new JSONObject();
        result.put("records", list);
        return result;
    }

    @Override
    public String save(String jsonData) {
        JSONObject jsonParams = FastJsonConvert.convertJSONToObject(jsonData, JSONObject.class);
        /*大区Id*/
        String bigAreaId = jsonParams.getString("bigAreaId");
        /*大区销售目标*/
        BigDecimal saleTargetNum = jsonParams.getBigDecimal("saleTargetNum");
        /*区域经理目标人数*/
        Integer managerTargerNum = jsonParams.getInteger("managerTargerNum");
        /*大区经理目标人数*/
        Integer bigManagerTargerNum = jsonParams.getInteger("bigManagerTargerNum");
        /*创建人*/
        String createUserId = jsonParams.getString("createUserId");
        /*大区经理Id*/
        String bigManagerId="";
        List<JSONObject> user2Region = user2RegionDao.getBigManageByRegionId(bigAreaId);
        if (user2Region.size()>0){
            JSONObject json=user2Region.get(0);
            bigManagerId = json.getString("userId");
        }
        String month = sdf.format(new Date());
        /*查询已完成数量*/
        BigDecimal saleFinishNum=bigachievementsDao.getSelFinishNumByBigAreaId(bigAreaId);
        //删除销售目标和用户目标表
        bigachievementsDao.removeByCondition(" AND BIG_AREA_ID=? AND MONTH=?", new String[]{bigAreaId,month});
        userAchievementsDao.removeByCondition(" AND BIG_AREA_ID=?", new String[]{bigAreaId});
        BigAchievementsEntity bigAchievementsEntity = new BigAchievementsEntity();
        UserAchievementsEntity userAchievementsEntity = new UserAchievementsEntity();
        if (StringUtils.isNotEmpty(bigAreaId)) {
            bigAchievementsEntity.setBigAreaId(bigAreaId);
        }
        if (StringUtils.isNotEmpty(bigManagerId)) {
            bigAchievementsEntity.setBigManagerId(bigManagerId);
        }
        bigAchievementsEntity.setMonth(month);
        if (saleTargetNum != null) {
            bigAchievementsEntity.setSaleTargetNum(saleTargetNum);
        }
        if (StringUtils.isNotEmpty(createUserId)) {
            bigAchievementsEntity.setCreateUserId(createUserId);
        }
        if (saleFinishNum!=null) {
            bigAchievementsEntity.setSaleFinishNum(saleFinishNum);
        }
        bigachievementsDao.add(bigAchievementsEntity);
            /*人员配置*/
        if (StringUtils.isNotEmpty(bigAreaId)) {
            userAchievementsEntity.setBigAreaId(bigAreaId);
        }
        if (bigManagerTargerNum != null) {
            userAchievementsEntity.setBigManagerTargerNum(bigManagerTargerNum);
        }
        if (managerTargerNum != null) {
            userAchievementsEntity.setManagerTargerNum(managerTargerNum);
        }
        if (StringUtils.isNotEmpty(createUserId)) {
            userAchievementsEntity.setCreateUserId(createUserId);
        }
        userAchievementsDao.add(userAchievementsEntity);
        /*同步修改组织机构处的配置人数*/
        RoleEntity roleEntity=new RoleEntity();
        List<String> roleNameList=new ArrayList<>();
        roleNameList.add("区域经理");
        roleNameList.add("大区经理");
        for (int i=0;i<roleNameList.size();i++){
            List<JSONObject> roleIdList=bigachievementsDao.getRoleIdByBigAreaIdAndRoleName(bigAreaId,roleNameList.get(i));
            if(roleNameList.get(i).equals("区域经理")){
                for (JSONObject list:roleIdList){
                    String roleId=list.getString("roleId");
                    roleEntity.setTargetNumber(managerTargerNum);
                    roleEntity.setId(roleId);
                    roleDao.update(roleEntity);
                }
            }else if (roleNameList.get(i).equals("大区经理")){
                for (JSONObject list:roleIdList){
                    String roleId=list.getString("roleId");
                    roleEntity.setTargetNumber(bigManagerTargerNum);
                    roleEntity.setId(roleId);
                    roleDao.update(roleEntity);
                }
            }
        }
        return bigAchievementsEntity.getId();
    }

    @Override
    public JSONObject delById(String jsonData) {
        JSONObject jsonParams = FastJsonConvert.convertJSONToObject(jsonData, JSONObject.class);
        String id = jsonParams.getString("id");
        Integer row = bigachievementsDao.delById(id);
        JSONObject obj = new JSONObject();
        if (row > 0) {
            obj.put("records", "删除成功");
        } else {
            obj.put("records", "删除失败");
        }
        return obj;
    }

    @Override
    public JSONObject removeById(String jsonData) {
        JSONObject jsonParams = FastJsonConvert.convertJSONToObject(jsonData, JSONObject.class);
        String id = jsonParams.getString("id");
        Integer row = bigachievementsDao.removeById(id);
        JSONObject obj = new JSONObject();
        if (row > 0) {
            obj.put("records", "删除成功");
        } else {
            obj.put("records", "删除失败");
        }
        return obj;
    }

    @Override
    public JSONObject getBigRegionTargetBycompanyId(String departName,String companyId) {
        return bigachievementsDao.getBigRegionTargetBycompanyId(departName,companyId);
    }

    @Override
    public JSONObject getForGroupVacantAndFine(String jsonData) {
        JSONObject jsonParams = FastJsonConvert.convertJSONToObject(jsonData, JSONObject.class);
        String companyId = jsonParams.getString("companyId");
        String day = jsonParams.getString("day");
        String month = day.substring(0, 7);
        StringBuffer condition=new StringBuffer();
        if (org.apache.commons.lang3.StringUtils.isNotBlank(companyId) && org.apache.commons.lang3.StringUtils.isNotEmpty(companyId)) {
            condition.append("AND companyId='" + companyId + "'\n" );
        }
        List<JSONObject> list = bigachievementsDao.getForGroupVacantAndFine(condition.toString(),month,day);
        JSONObject result = new JSONObject();
        result.put("records", list);
        return result;
    }

    @Override
    public JSONObject getRoleChangeDate(String jsonData) {
        JSONObject jsonParams = FastJsonConvert.convertJSONToObject(jsonData, JSONObject.class);
        String companyId=jsonParams.getString("companyId");
        String userId=jsonParams.getString("userId");
        String roleName=jsonParams.getString("roleName");
        JSONObject roleChangeDate=bigachievementsDao.getRoleChangeDate(companyId,userId,roleName);
        return roleChangeDate;
    }

    @Override
    public  List<JSONObject> getDownByCondition(String companyId, String day) {
        String month = day.substring(0, 7);
        StringBuffer condition=new StringBuffer();
        if (org.apache.commons.lang3.StringUtils.isNotBlank(companyId) && org.apache.commons.lang3.StringUtils.isNotEmpty(companyId)) {
            condition.append("AND companyId='" + companyId + "'\n" );
        }
        List<JSONObject> list = bigachievementsDao.getForGroupVacantAndFine(condition.toString(),month,day);
        return list;
    }




}
